package com.r2dbc.common;

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import reactor.core.publisher.Mono;

/**
 * 接口返回数据格式
 *
 * @author scott
 * @date 2019年1月19日
 */
@Data
@Builder
@AllArgsConstructor
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private static final int SUCCESS = 200;
    private static final int ERROR = 500;

    /**
     * 成功标志
     */
    private boolean success = true;

    /**
     * 返回处理消息
     */
    private String message;

    /**
     * 返回代码
     */
    private int code;

    /**
     * 返回数据对象 data
     */
    private T result;

    /**
     * 时间戳
     */
    private long timestamp = System.currentTimeMillis();
    @JsonIgnore
    private String onlTable;

    public Result() {

    }


    public static <T> Mono<Result<T>> ok(Mono<T> data) {
        return data.map(t -> {
            Result<T> r = new Result<T>();
            r.setSuccess(true);
            r.setCode(SUCCESS);
            r.setResult(t);
            return r;
        });

    }

    public static <T> Mono<Result<T>> ok(String msg) {
        Result<T> r = new Result<T>();
        r.setSuccess(true);
        r.setCode(SUCCESS);
        return Mono.just(r);
    }

    public static <T> Mono<Result<T>> error(Mono<T> data) {
        return data.map(t -> {
            Result<T> r = new Result<T>();
            r.setSuccess(false);
            r.setCode(ERROR);
            r.setResult(t);
            return r;
        });
    }

    public static <T> Mono<Result<T>> error() {
        Result<T> r = new Result<T>();
        r.setSuccess(false);
        r.setCode(ERROR);
        return Mono.just(r);
    }

    public static <T> Mono<Result<T>> error(String msg) {
        Result<T> r = new Result<T>();
        r.setSuccess(false);
        r.setCode(ERROR);
        r.setMessage(msg);
        return Mono.just(r);
    }


    public static <T> Mono<Result<T>> error(String msg, Mono<T> data) {
        return data.map(t -> {
            Result<T> r = new Result<T>();
            r.setSuccess(false);
            r.setCode(ERROR);
            r.setMessage(msg);
            r.setResult(t);
            return r;
        });
    }


}